<?php

namespace app\admin\controller;

use app\admin\model\Question;
use app\common\controller\Backend;
use app\common\model\QuestionPaper;
use think\Db;

/**
 * 刷题组卷
 *
 * @icon fa fa-circle-o
 */
class Questiongroup extends Backend
{

    /**
     * Questiongroup模型对象
     * @var \app\admin\model\Questiongroup
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Questiongroup;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row['question_cate_name'] = Db::name('question_cate')->where('id', $row['question_cate_id'])->value('name') ?? '';
                $row['question_cate_pid_name'] = Db::name('question_cate')->where('id', $row['question_cate_pid'])->value('name') ?? '';
                $row['question_cate_id3_name'] = Db::name('question_cate')->where('id', $row['question_cate_id3'])->value('name') ?? '';
            }
            $count = $list->total();
            $items = $list->items();
            $result = array("total" => $count, "rows" => $items);
            return json($result);
        }
        $question_menu_id = $this->request->get('question_menu_id', 0);
        $this->assign("question_menu_id", $question_menu_id);
        return $this->view->fetch();
    }



    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $params['questions'] = json_decode($params['questions'], true);
                if (!$params['questions']) {
                    $this->error('请先选择题目');
                }
                if ($params['question_cate_id3']) {
                    $params['test_paper'] = 1;
                }
                if ($params['num'] > count($params['questions'])) {
                    $this->error('每组题提交数不能大于题目数量');
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    # 固定选题
                    $this->saveFixQuestion($this->model, $params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['questions'] = json_decode($params['questions'], true);
            if (!$params['questions']) {
                $this->error('请先选择题目');
            }
            if ($params['question_cate_id3']) {
                $params['test_paper'] = 1;
            }
            if ($params['num'] > count($params['questions'])) {
                $this->error('每组题提交数不能大于题目数量');
            }
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $row->allowField(true)->save($params);
                    $this->saveFixQuestion($row, $params, 'edit');
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        # 编辑回显 固定选题
        $row['questions'] = Question::getFixListByPaper($row['id'], ['mock']);
        # 编辑回显固定选题模式
        $row['mode'] = 'FIX';
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 固定选题
     */
    protected function saveFixQuestion($questionGroup, $params, $method = 'add')
    {
        # 固定选题
        $questionPaper = (new QuestionPaper());
        if ($method == 'edit') {
            $questionPaper::where('question_group_id', $questionGroup['id'])->delete();
        }
        $questions = $params['questions'];
        $data = ['questionGroup' => $questionGroup, 'questions' => $questions];
        $dd = $this->model->addFixQuestion($data);
        # 走消息队列
        // Queue::push(ExamQuestion::class, $data);
        return;
    }




    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                # 删除 question_paper 表数据
                Db::name('question_paper')->where('question_group_id', $item['id'])->delete();
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
